package third.lib.wx.common.utils;

import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import third.lib.common.exception.ThirdException;
import third.lib.common.status.ThirdStatus;
import third.lib.utils.DateTimeUtils;
import third.lib.utils.EncryptUtils;
import third.lib.utils.StringRandUtils;

import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.FileInputStream;
import java.nio.charset.Charset;
import java.security.KeyStore;
import java.util.*;

public class WXUtils {
    public static String sign(SortedMap<String, Object> parameters, String key) throws ThirdException {
        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();
        Iterator it = es.iterator();

        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            Object v = entry.getValue();
            if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }

        sb.append("key=" + key);
        String sign = "";

        try {
            sign = EncryptUtils.MD5Encode(sb.toString());
            return sign;
        } catch (Exception var8) {
            var8.printStackTrace();
            throw new ThirdException(ThirdStatus.WX);
        }
    }

    public static RestTemplate getRestTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        List<HttpMessageConverter<?>> httpMessageConverters = restTemplate.getMessageConverters();
        httpMessageConverters.stream().forEach((httpMessageConverter) -> {
            if (httpMessageConverter instanceof StringHttpMessageConverter) {
                StringHttpMessageConverter messageConverter = (StringHttpMessageConverter)httpMessageConverter;
                messageConverter.setDefaultCharset(Charset.forName("UTF-8"));
            }

        });
        return restTemplate;
    }

    public static RestTemplate getRestTemplateWithCert(String cetPath, String pwd) throws ThirdException {
        RestTemplate restTemplate = null;

        try {
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            FileInputStream instream = new FileInputStream(new File(cetPath));
            keyStore.load(instream, pwd.toCharArray());
            SSLContext sslcontext = SSLContextBuilder.create().loadKeyMaterial(keyStore, pwd.toCharArray()).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1"}, (String[])null, NoopHostnameVerifier.INSTANCE);
            CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
            HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
            restTemplate = new RestTemplate(factory);
            List<HttpMessageConverter<?>> httpMessageConverters = restTemplate.getMessageConverters();
            httpMessageConverters.stream().forEach((httpMessageConverter) -> {
                if (httpMessageConverter instanceof StringHttpMessageConverter) {
                    StringHttpMessageConverter messageConverter = (StringHttpMessageConverter)httpMessageConverter;
                    messageConverter.setDefaultCharset(Charset.forName("UTF-8"));
                }

            });
            return restTemplate;
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new ThirdException(ThirdStatus.WX);
        }
    }

    public static String getNonceStr() {
        return StringRandUtils.randNumberAndChar(32).toUpperCase();
    }

    public static String getTradeNo() {
        return DateTimeUtils.getMillis() + StringRandUtils.randNumberAndChar(19);
    }

    public static String getReadPacketTradeNo() {
        return DateTimeUtils.getMillis() + StringRandUtils.randNumberAndChar(15);
    }

    public static String mapToStr(SortedMap<String, Object> map, String sign) {
        StringBuffer bf = new StringBuffer();
        bf.append("<xml>");
        Iterator itor = map.entrySet().iterator();

        while(itor.hasNext()) {
            Map.Entry<String, Object> entry = (Map.Entry)itor.next();
            bf.append(String.format("<%s><![CDATA[%s]]></%s>", entry.getKey(), entry.getValue(), entry.getKey()));
        }

        bf.append("<sign><![CDATA[");
        bf.append(sign);
        bf.append("]]></sign>");
        bf.append("</xml>");
        return bf.toString();
    }
}
